from fastapi import APIRouter, HTTPException, Depends, Request
from pydantic import BaseModel
from typing import Dict, Any
from scorpio.core.common import get_logger
from scorpio.services.database import DatabaseInitializerService
from scorpio.shared import get_db_initializer

logger = get_logger(__name__)

# 创建数据库管理路由器
db_router = APIRouter(prefix="/api", tags=["数据库管理"])

def get_application_env(request: Request)->str:
    return request.app.state.config.environment
class DatabaseInitResponse(BaseModel):
    status: str
    message: str
    details: Dict[str, Any]

class DatabaseHealthResponse(BaseModel):
    status: str
    details: Dict[str, Any]

@db_router.post("/database/init", response_model=DatabaseInitResponse)
async def initialize( db_initializer: DatabaseInitializerService = Depends(get_db_initializer)):
    """手动初始化数据库"""
    try:
        logger.info(f"initialize database with api: /v1/database/init")
        success = await db_initializer.initialize()
        if success:
            return DatabaseInitResponse(
                status="success",
                message="数据库初始化完成",
                details={}
            )
        else:
            return DatabaseInitResponse(
                status="error",
                message="数据库初始化失败",
                details={}
            )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"数据库初始化失败: {str(e)}")


@db_router.get("/database/stats")
async def get_database_stats(db_initializer: DatabaseInitializerService = Depends(get_db_initializer)):
    """获取数据库统计信息"""
    try:
        logger.info("start to get database stats")
        stats = await db_initializer.get_database_stats()
        return stats
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取统计信息失败: {str(e)}")

@db_router.get("/database/schema")
async def get_database_schema(db_initializer: DatabaseInitializerService = Depends(get_db_initializer)):
    """获取数据库模式信息"""
    try:
        schema_info = await db_initializer.get_database_schema_info()
        return schema_info
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取模式信息失败: {str(e)}")

@db_router.post("/database/reset")
async def reset_database(application_env: str = Depends(get_application_env), db_initializer: DatabaseInitializerService = Depends(get_db_initializer)):
    """重置数据库（仅用于开发环境）"""
    
    if application_env == "production":
        raise HTTPException(status_code=403, detail="生产环境禁止重置数据库")
    
    try:
        logger.info("start to reset database")
        await db_initializer.reset(application_env)
        return {"status": "success", "message": "数据库已重置"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"数据库重置失败: {str(e)}")

@db_router.get("/health", response_model=DatabaseHealthResponse)
async def get_health(db_initializer: DatabaseInitializerService = Depends(get_db_initializer)):
    """获取数据库健康状态"""
    try:
        logger.info("start to check database health")
        await db_initializer.initialize()
        health_info = await db_initializer.check_database_health()
        return DatabaseHealthResponse(
            status=health_info["status"],
            details=health_info
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"健康检查失败: {str(e)}")
